﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Telerik.Web.UI;
using System.Text.RegularExpressions;

namespace BSPortal.Usercontrol.Admin.Book
{
    public partial class Category : System.Web.UI.UserControl
    {
        private short id = 0;
        private MainService service = new MainService();
        protected const string unreadPattern = @"\(\d+\)";

        protected void RadTreeView1_ContextMenuItemClick(object sender, RadTreeViewContextMenuEventArgs e)
        {
            RadTreeNode clickedNode = e.Node;

            switch (e.MenuItem.Value)
            {
                case "Copy":
                    RadTreeNode clonedNode = clickedNode.Clone();
                    clonedNode.Text = string.Format("Copy of {0}", clickedNode.Text);
                    clickedNode.InsertAfter(clonedNode);
                    //set node's value so we can find it in startNodeInEditMode
                    clonedNode.Value = clonedNode.GetFullPath("/");
                    clonedNode.Selected = true;
                    startNodeInEditMode(clonedNode.Value);
                    break;
                case "NewFolder":
                    RadTreeNode newFolder = new RadTreeNode(string.Format("New Folder {0}", clickedNode.Nodes.Count + 1));
                    newFolder.Selected = true;
                    newFolder.ImageUrl = clickedNode.ImageUrl;
                    clickedNode.Nodes.Add(newFolder);
                    clickedNode.Expanded = true;
                    //set node's value so we can find it in startNodeInEditMode
                    newFolder.Value = "0";
                    startNodeInEditMode(newFolder.Value);
                    //service.CreateCateogry(clickedNode.Text, "", short.Parse(e.Node.Value));
                    break;
                case "EmptyFolder":
                    emptyFolder(clickedNode, true);
                    break;
                case "MarkAsRead":
                    emptyFolder(clickedNode, false);
                    break;
                case "Delete":
                    if (clickedNode.Value == "1" || clickedNode.Value == "2" || clickedNode.Value == "3")
                    {
                        return;
                    }
                    clickedNode.Remove();
                    service.DeleteCategory(short.Parse(e.Node.Value));
                    LoadCategory();
                    break;
                case "Rename":
                    //service.UpdateCategory(short.Parse(e.Node.Value),e.Node.Text,"")
                    break;
            }
        }

        private void startNodeInEditMode(string nodeValue)
        {
            //find the node by its Value and edit it when page loads

            string js = "Sys.Application.add_load(editNode); function editNode(){ ";
            js += "var tree = $find(\"" + RadTreeView1.ClientID + "\");";
            js += "var node = tree.findNodeByValue('" + nodeValue + "');";
            js += "if (node) node.startEdit();";
            js += "Sys.Application.remove_load(editNode);};";

            RadScriptManager.RegisterStartupScript(Page, Page.GetType(), "nodeEdit", js, true);
        }

        protected void RadTreeView1_NodeEdit(object sender, RadTreeNodeEditEventArgs e)
        {
            if(e.Node.Value=="1" || e.Node.Value=="2" || e.Node.Value=="3")
            {
                e.Text = e.Node.Text;
                return;
            }
            e.Node.Text = e.Text;
            if (e.Node.Value == "0")
            {
                service.CreateCateogry(e.Text, "", short.Parse(e.Node.ParentNode.Value), true);
                var item = service.GetCategoryByName(e.Text);
                e.Node.Value = item.CategoryId.ToString();
            }
            else
            {
                service.UpdateCategory(short.Parse(e.Node.Value), e.Text, "", short.Parse(e.Node.ParentNode.Value), true);
            }
        }

        //this method is used by Mark All as Read and Empty this folder 
        protected void emptyFolder(RadTreeNode node, bool removeChildNodes)
        {
            node.Font.Bold = false;
            node.Text = Regex.Replace(node.Text, unreadPattern, "");

            if (removeChildNodes)
            {
                //Empty this folder is clicked
                for (int i = node.Nodes.Count - 1; i >= 0; i--)
                {
                    node.Nodes.RemoveAt(i);
                }
            }
            else
            {
                //Mark all as read is clicked
                foreach (RadTreeNode child in node.Nodes)
                {
                    emptyFolder(child, removeChildNodes);
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!IsPostBack)
            {
                LoadCategory();
            }
        }

        private void LoadCategory()
        {
            RadTreeNode nodeBookRoot = new RadTreeNode("Sách", "1");
            RadTreeNode nodeElectronicRoot = new RadTreeNode("Thiết bị điện tử", "2");
            RadTreeNode nodeHouseRoot = new RadTreeNode("Đồ gia dụng", "3");
            nodeBookRoot.AllowEdit=false;
            nodeElectronicRoot.AllowEdit = false;
            nodeHouseRoot.AllowEdit = false;
            RadTreeNode nodeBook = GetAllNodeByListCategory(nodeBookRoot, 1);
            RadTreeNode nodeElectronic = GetAllNodeByListCategory(nodeElectronicRoot, 2);
            RadTreeNode nodeHouse = GetAllNodeByListCategory(nodeHouseRoot, 3);
            RadTreeView1.Nodes.Clear();
            RadTreeView1.Nodes.Add(nodeBookRoot);
            RadTreeView1.Nodes.Add(nodeElectronicRoot);
            RadTreeView1.Nodes.Add(nodeHouseRoot);
        }

        public RadTreeNode GetAllNodeByListCategory(RadTreeNode root, short parentCategoyId)
        {
            var radeNode = new RadTreeNode();
            var listCategory = service.GetListChildCategoryByParent(parentCategoyId);

            foreach (var category in listCategory)
            {
                var node = new RadTreeNode(category.Name, category.CategoryId.ToString());
                root.Nodes.Add(node);
                RadTreeNode node2 = GetAllNodeByListCategory(node, category.CategoryId);
            }
            return radeNode;
        }
    }
}